package com.ad.pet.app.address;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Switch;
import android.widget.TextView;

import com.ad.pet.DaggerMainActivityCompent;
import com.ad.pet.R;
import com.ad.pet.app.Navigation;
import com.ad.pet.app.RxDisposable;
import com.ad.pet.common.data.utils.ui.DialogUtil;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.common.structure.PermissionManager;
import com.ad.pet.common.structure.events.RxBus;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.common.structure.ui.activity.AppToolbarActivity;
import com.ad.pet.constant.Constant;
import com.ad.pet.models.remote.address.Address;
import com.ad.pet.models.remote.address.City;
import com.ad.pet.models.remote.address.District;
import com.ad.pet.models.remote.address.Province;
import com.ad.pet.models.remote.login.Country;
import com.ad.pet.ui.pickerview.OptionsPickerView;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by SEELE on 2018/6/25.
 */

public class AddressDetailActivity extends AppToolbarActivity implements AddressContract.View {

    @BindView(R.id.et_reciver)
    EditText mEtReciver;
    ;
    @BindView(R.id.et_phone)
    EditText mEtPhone;
    @BindView(R.id.tv_area)
    TextView mTvArea;

    @BindView(R.id.tv_detail_address)
    EditText mTvDetailAddress;
    @BindView(R.id.rg_group)
    RadioGroup mRbGroup;


    @BindView(R.id.switch_default)
    Switch mSwitchDefault;

    @BindView(R.id.btn_commit)
    Button mBtnCommit;


    @Inject
    PermissionManager mPermissionManager;
    @Inject
    RxDisposable mRxDisposable;
    @BindView(R.id.rb_home)
    RadioButton rbHome;
    @BindView(R.id.rb_company)
    RadioButton rbCompany;
    @BindView(R.id.rb_school)
    RadioButton rbSchool;

    private Address mAddress;
    private Country mCountry;
    private Country mCountry2;
    private Country mCountry3;
    @Inject
    AddressPresenter mAddressPresenter;
    private boolean mIsDel;

    private ArrayList<Country> mCountryArrayList;
    ProgressDialog mLoadingDialog;

    @BindView(R.id.tv_chose_city)
    TextView mTvChoseCity;


    private List<Province> mProvinces;
    private boolean mIsCheck;

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        mStatusLayoutManager.showContent();
        mToolbar.setTitle(getString(R.string.add_shouhuo_address));
    }

    @Override
    protected int contentLayout() {
        return R.layout.activity_address_detail;
    }

    @Override
    protected void clickRetry(View v) {

    }

    @Override
    protected void initViews() {
        mLoadingDialog = DialogUtil.createProgressDialog(mActivity, getString(R.string.loading));
        mPermissionManager.setRxPermissions(new RxPermissions(this));
        mAddress = (Address) getIntent().getSerializableExtra("address");
        mIsCheck = getIntent().getBooleanExtra(Constant.IS_CHECK, false);

        mCountryArrayList = new ArrayList<>();


        if (mAddress != null) {
            mEtReciver.setText(mAddress.getConsigner());
            mEtPhone.setText(mAddress.getMobile());
            mTvChoseCity.setText(mAddress.getProvince_name() + mAddress.getCity_name() + mAddress.getDistrict_name());
            mTvDetailAddress.setText(mAddress.getAddress());
            switch (mAddress.getLabel()) {
                case 1:
                    rbHome.setChecked(true);
                    break;
                case 2:
                    rbCompany.setChecked(true);
                    break;
                case 3:
                    rbSchool.setChecked(true);
                    break;
            }

            mSwitchDefault.setChecked(mAddress.getIs_default()==1);


        }else
        {
            mAddress = new Address();
        }

    }

    @Override
    protected void initData() {
        mAddressPresenter.onCreate(this);
        mAddressPresenter.getCountryProvence();
    }

    @Override
    protected void initEvents() {
//        mIvBook.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mRxDisposable.add(mPermissionManager.checkPermissionShowNick(new Action1<Permission>() {
//                    @Override
//                    public void call(Permission permission) {
//                        Navigation.goContractBook(mActivity, 1);
//                    }
//                }, getString(R.string.red_contact_books), Manifest.permission.READ_CONTACTS));
//
//            }
//        });
        mTvChoseCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mProvinces == null || mProvinces.size() == 0) {
                    return;
                }
                final List<List<City>> list1 = new ArrayList<>();
                for (int i = 0; i < mProvinces.size(); i++) {
                    list1.add(mProvinces.get(i).getChild());
                }
                final List<List<List<District>>> list2 = new ArrayList<>();
                for (int i = 0; i < list1.size(); i++) {
                    List<List<District>> tempList = new ArrayList<>();
                    for (int j = 0; j < list1.get(i).size(); j++) {
                        tempList.add(list1.get(i).get(j).getChild());
                    }
                    list2.add(tempList);
                }
                OptionsPickerView pvOptions = new OptionsPickerView.Builder(mActivity, new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3, View v) {
                        mTvChoseCity.setText(mProvinces.get(options1).getProvince_name()+list1.get(options1).get(option2).getCity_name()+list2.get(options1).get(option2).get(options3));
                        mAddress.setProvince(mProvinces.get(options1).getProvince_id());
                        mAddress.setCity(list1.get(options1).get(option2).getCity_id());
                        mAddress.setDistrict(list2.get(options1).get(option2).get(options3).getDistrict_id());
                    }
                }).build();
                pvOptions.setPicker(mProvinces,list1,list2);//添加数据源
                pvOptions.setSelectOptions(1);
                pvOptions.show();
            }
        });
        mTvArea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigation.goChoseCountry(mActivity, 3);
            }
        });

    mRbGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId){
                case R.id.rb_home:
                    mAddress.setLabel(1);
                    break;
                case R.id.rb_company:
                    mAddress.setLabel(2);
                        break;
                case R.id.rb_school:
                    mAddress.setLabel(3);
                    break;
            }
        }
    });
    mSwitchDefault.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mAddress.setIs_default(isChecked?1:0);
        }
    });
        mBtnCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mEtReciver.getText().toString())) {
                    ToastUtil.getToastUtil().showShort(mEtReciver.getHint().toString());
                    return;
                }

                if (TextUtils.isEmpty(mEtPhone.getText().toString())) {
                    ToastUtil.getToastUtil().showShort(mEtPhone.getHint().toString());
                    return;
                }

                if (TextUtils.isEmpty(mTvChoseCity.getText().toString())) {
                    ToastUtil.getToastUtil().showShort(mTvChoseCity.getHint().toString());
                    return;
                }


                if (TextUtils.isEmpty(mTvDetailAddress.getText().toString())) {
                    ToastUtil.getToastUtil().showShort("请输入"+mTvDetailAddress.getHint().toString());
                    return;
                }



                mAddress.setConsigner(mEtReciver.getText().toString());
                mAddress.setMobile(mEtPhone.getText().toString());
                mAddress.setAddress(mTvDetailAddress.getText().toString());


               if (TextUtils.isEmpty(mAddress.getId())) {

                  mAddressPresenter.addAddress(mAddress.getConsigner(),mAddress.getMobile(),mAddress.getProvince(),mAddress.getCity(),mAddress.getDistrict(),mAddress.getAddress(),mAddress.getLabel()+"",mAddress.getIs_default());

           } else {
                mAddressPresenter.updataAddress(mAddress.getId(),mAddress.getConsigner(),mAddress.getMobile(),mAddress.getProvince(),mAddress.getCity(),mAddress.getDistrict(),mAddress.getAddress(),mAddress.getLabel()+"",mAddress.getIs_default());

             }
            }
        });
//        mTvDeleteAddress.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                DialogUtil.createDialog(mActivity, "", getString(R.string.sure_delete_item_address), true, getString(R.string.cancel), new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//
//                    }
//                }, getString(R.string.confirm), new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
////                        mAddressPresenter.delAddress(mAddress.getId());
//                    }
//                }).show();
//            }
//        });


//        mTvProvice.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (mProvinces == null)
//                    return;
//                List<String> provinces = new ArrayList<>();
//                for (int i = 0; i < mProvinces.size(); i++) {
//                    provinces.add(mProvinces.get(i).getName());
//                }
//                OptionsPickerView pvOptions = new OptionsPickerView.Builder(mActivity, new OptionsPickerView.OnOptionsSelectListener() {
//                    @Override
//                    public void onOptionsSelect(int options1, int option2, int options3, View v) {
//                        mCities = mProvinces.get(options1).getCity_list();
//                        mTvProvice.setText(mProvinces.get(options1).getName());
//                        mTvProvice.setTag(mProvinces.get(options1).getId());
//                        mTvCity.setText("");
//
//                    }
//                }).build();
//                pvOptions.setPicker(provinces);//添加数据源
//                if (provinces.size() > 1) {
//                    pvOptions.setSelectOptions(1);
//                }
//
//                pvOptions.show();
//            }
//        });


    }

    @Override
    public void initInject() {
        DaggerMainActivityCompent.builder().applicationComponent(getApplicationComponent()).activityModule(getActivityModule()).build().inject(this);
    }

    @Override
    protected BasePresenter getPresenter() {
        return mAddressPresenter;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String name = "";
        String phoneNumber = "";
        switch (resultCode) {
            case RESULT_OK:
                switch (requestCode) {
                    case 1:
                        if (data == null) {
                            return;
                        }
                        Uri contactData = data.getData();
                        if (contactData == null) {
                            return;
                        }
                        Cursor cursor = managedQuery(contactData, null, null, null,
                                null);
                        if (cursor.moveToFirst()) {
                            name = cursor
                                    .getString(cursor
                                            .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                            String hasPhone = cursor
                                    .getString(cursor
                                            .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                            String id = cursor.getString(cursor
                                    .getColumnIndex(ContactsContract.Contacts._ID));
                            if (hasPhone.equalsIgnoreCase("1")) {
                                hasPhone = "true";
                            } else {
                                hasPhone = "false";
                            }
                            if (Boolean.parseBoolean(hasPhone)) {
                                Cursor phones = getContentResolver()
                                        .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                                null,
                                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                                        + " = " + id, null, null);
                                while (phones.moveToNext()) {
                                    phoneNumber = phones
                                            .getString(phones
                                                    .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                                }
                                mEtReciver.setText(name);
                                mEtPhone.setText(phoneNumber.replaceAll(" ", ""));

                                if (Build.VERSION.SDK_INT < 14) {
                                    //只有4.0以下才需要手动关闭
                                    phones.close();
                                }

                            }

                            if (Build.VERSION.SDK_INT < 14) {
                                //只有4.0以下才需要手动关闭
                                cursor.close();
                            }

                        }


                        break;

                    case 2:
                        mCountry = (Country) data.getSerializableExtra("country");
                        break;
                    case 3:
                        mCountry2 = (Country) data.getSerializableExtra("country");

                        break;
                    case 4:
                        mCountry3 = (Country) data.getSerializableExtra("country");

                        break;
                }
                break;

        }
    }


    @Override
    public void finish() {
        if (!mIsDel) {
            DialogUtil.createDialog(mActivity, getString(R.string.is_cancel_add_shou_huo_dizhi), getString(R.string.confirm), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    AddressDetailActivity.super.finish();
                }
            }).show();
        } else {
            super.finish();
        }

    }

    @Override
    public void showLoading() {
        mLoadingDialog.show();
    }

    @Override
    public void hideLoading() {
        mLoadingDialog.dismiss();
    }

    @Override
    public void error(String msg) {
        mLoadingDialog.dismiss();
    }

    @Override
    public void error(int code, String msg) {
        mLoadingDialog.dismiss();
        ToastUtil.getToastUtil().showShort(msg);
    }


    @Override
    public void getAddresssListSuccess(List<Address> addressList) {

    }

    @Override
    public void getUpdateAddressSuccess() {
        if (!mIsCheck) {
//            mAddress.setId(user.getAddress_id());
            RxBus.getDefault().post(mAddress);
        }

        ToastUtil.getToastUtil().showShort(getString(R.string.add_address_success));
        mIsDel = true;
        finish();
    }

    @Override
    public void delAddressSuccess() {
        ToastUtil.getToastUtil().showShort(getString(R.string.delete_address_success));
        mIsDel = true;
        finish();
    }

    @Override
    public void getCountryProvenceSuccess(List<Province> list) {
        mProvinces = list;


    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
